import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:squat_easy/se_coin_shop/se_coin_shop_page.dart';
import 'package:squat_easy/se_db/se_db_dao.dart';
import 'package:squat_easy/se_db/se_db_database.dart';
import 'package:squat_easy/se_db/se_db_entity.dart';
import 'package:squat_easy/se_net/se_global_url.dart';
import 'package:squat_easy/se_net/se_net.dart';
import 'package:squat_easy/se_route.dart';
import 'package:squat_easy/se_service/se_user_service.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeApiHome extends SeApi {
  SeApiHome.consumeCoin({required int num})
      : super(
          SeGlobalUrl.consumeCoin,
          params: {'outlay': num, 'source': 'iap'},
        );
}

class SeHomeLogic extends GetxController with CommonLife {
  bool isEdit = false;

  ///group
  final TextEditingController groupFrontController = TextEditingController();
  final TextEditingController groupBackController = TextEditingController();

  ///times
  final TextEditingController timesController = TextEditingController();

  ///seconds
  final TextEditingController secondsController = TextEditingController();

  ///days
  final TextEditingController daysController = TextEditingController();

  ///daily training
  final TextEditingController dailyTrainingController = TextEditingController();

  int freeCount = 0;

  late final SeAppDatabase database;
  late final TrainingDao dao;

  String get userId => SeUserService.instance.userId;

  GroupedTraining recentlyRun = GroupedTraining(groupDate: 'Recently run', trainings: []);

  @override
  void onReady() async {
    super.onReady();

    final database = await $FloorSeAppDatabase.databaseBuilder(SeDbConstant.databaseName).build();
    final dao = database.trainingDao;

    this.dao = dao;
    this.database = database;

    ///recent取最近3条数据
    freeCount = CommonStorage().getInt(SeUserService.instance.freeRecogniseCountKey);
    recentlyRun.trainings = await getRecentTraining();
    update();
  }

  Future<List<Training>> getRecentTraining() async => dao.findLastTrainingByUserId(userId, 3);

  void toggleEdit() {
    isEdit = !isEdit;
    if (!isEdit) CommonOperate.hideKeyboard();
    update();
  }

  void recognise() async {
    if (groupFrontController.text.empty ||
        groupBackController.text.empty ||
        timesController.text.empty ||
        secondsController.text.empty ||
        daysController.text.empty ||
        dailyTrainingController.text.empty) {
      Loading.toast('Please fill in completely.');
      return;
    }

    CommonOperate.hideKeyboard();

    if (freeCount > 0) {
      ///消费免费次数
      freeCount--;
      await CommonStorage().setInt(SeUserService.instance.freeRecogniseCountKey, freeCount);
      Training? result = await saveToDb();
      insert(result);
      update();
    } else {
      ///扣费
      Loading.show(clickMaskDismiss: false);
      await SeApiHome.consumeCoin(num: 3).post().then((value) async {
        SeUserService.instance.getCacheMineInfoBean(true);
        Training? result = await saveToDb();
        insert(result);
        update();
      }).catchError((e) {
        Loading.toast(e.toString());
      }).whenComplete(() {
        Loading.dismiss();
      });
    }
  }

  void insert(Training? training) {
    if (training == null) return;
    recentlyRun.trainings.insert(0, training);
    recentlyRun.trainings = recentlyRun.trainings.take(3).toList();
  }

  Future<Training?> saveToDb() async {
    DateTime now = DateTime.now();
    String createTime = '${now.year}-${now.month}-${now.day}';
    String dailyTraining = dailyTrainingController.text;
    try {
      var training = Training(
        userId: userId,
        groupPrefix: int.tryParse(groupFrontController.text) ?? 0,
        groupSuffix: int.tryParse(groupBackController.text) ?? 0,
        times: int.tryParse(timesController.text) ?? 0,
        seconds: int.tryParse(secondsController.text) ?? 0,
        days: int.tryParse(daysController.text) ?? 0,
        dailyTraining: dailyTraining,
        createTime: createTime,
      );

      ///insert data
      await dao.insertTraining(training);

      ///update training
      await dao.updateTrainingByDateTime(userId, createTime, dailyTraining);

      ///clear input
      clearInput();

      return training;
    } catch (e) {
      return null;
    }
  }

  void clearInput() {
    groupFrontController.clear();
    groupBackController.clear();
    timesController.clear();
    secondsController.clear();
    daysController.clear();
    dailyTrainingController.clear();
  }

  @override
  void onClose() {
    super.onClose();
    groupFrontController.dispose();
    groupBackController.dispose();
    timesController.dispose();
    secondsController.dispose();
    daysController.dispose();
    dailyTrainingController.dispose();
  }

  @override
  void pageBack() {
    super.pageBack();
  }
}

class GroupedTraining {
  String groupDate;
  List<Training> trainings;

  GroupedTraining({
    required this.groupDate,
    required this.trainings,
  });
}
